const url = 'ws://192.168.0.29:3000';
let ws = null;
// let username = window.prompt('请输入你的名称', '')
// let noticeText = document.querySelector('#noticeText')
let playerUsernameList = new Set() // 在线用户集合
let playerList = [] // 在线摩尔实例集合
let newPlayerY
let newPlayerX
// 心跳检测
let heartCheck = {
    // 每隔几秒测试一下心跳是否在继续
    timeout: 15000,
    timeoutObj: null,
    serverTimeoutObj: null,
    start: function () 
    {
        // console.log('开始测试心跳');
        // eslint-disable-next-line @typescript-eslint/no-this-alias
        let self = this;
        this.timeoutObj && clearTimeout(this.timeoutObj);
        this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
        this.timeoutObj = setTimeout(function ()
        {
            // 这里发送一个心跳，后端收到后，返回一个心跳消息，
            // console.log('发送消息，测试后台是否运行中...');
            // 任意发一个消息过去，后台接收，在init()中的onmessage收到消息，说明后台没有挂掉，有心跳
            send({code:'1001'});
            self.serverTimeoutObj = setTimeout(function () 
            {
                console.log('没有心跳了....');
                ws.close();
            }, self.timeout);

        }, this.timeout);

    }  
};

// 创建websocket连接
function createWebSocket (onMessage, onError, onClose)
{
    try 
    {
        ws = new WebSocket(url);
        ws.onopen = () => 
        {
            // 连接时发送状态即可
            const userData = {
                code: '0'
            };
            send(userData);
            // 心跳重置
            heartCheck.start();
        };
    
        // 客户端接收消息
        ws.onmessage = (event) => 
        {
            let msg = JSON.parse(event.data);
            // if (msg.code === 100)
            // {
            //     message.success('连接成功');
            // }
            onMessage && onMessage(msg);
            heartCheck.start();
        };
    
        // 出错
        ws.onerror = (error) => 
        {
            console.log('连接出错' + error.message);
            onError && onError(error);
        };
    
        ws.onclose = (code) => 
        {
            console.log('连接断开' + code);
            onClose && onClose(code);
        };
    } 
    catch (err) 
    {
        console.log('webSocket异常' + err.message);
    }
}

function send (msgObj) 
{
    // 发送消息的时候触发
    ws.send(JSON.stringify(msgObj));
}

// 关闭连接
function closeWebSocket ()
{
    ws.close();
}

  
function receiveWebSocket ()
{
    if (!config.isOnline) 
    {
        // 直接创建摩尔实例
        player = new Sprite({
            name:'username',
            position: {
                x: playerPos.x,
                y: playerPos.y,
                originX: playerPos.x,
                originY: playerPos.y
            },
            image: playerDownImage,
            toward:'down',
            frames: {
                max: 5,
                hold: 10
            },
            sprites: {
                up: playerUpImage,
                left: playerLeftImage,
                right: playerRightImage,
                down: playerDownImage
            },
            scale:0.8
        })
        return
    }
    if (isLogin)
    {
        createWebSocket((message) => {
            if (message.code === '0')
            {
                // 连接成功，加载服务器列表
                console.log('连接成功')
            }
            if (message.code === '1')
            {
                // 进入游戏，生成摩尔
                isConnectSocket = true
                // noticeText.innerHTML += `${message.username}进入游戏<br>`;
                if (message.username === username)
                {
                    let playerInfo = new Sprite({
                        name:message.username,
                        position: {
                            x: playerPos.x,
                            y: playerPos.y,
                            originX: playerPos.x,
                            originY: playerPos.y
                        },
                        image: playerDownImage,
                        toward:'down',
                        frames: {
                            max: 5,
                            hold: 10
                        },
                        sprites: {
                            up: playerUpImage,
                            left: playerLeftImage,
                            right: playerRightImage,
                            down: playerDownImage
                        },
                        scale:0.8
                    })
                    player = playerInfo // 保存自己的模型
                    // createCurrentMap() // 创建地图
                    // animate()
                    console.log(player);
                    newPlayerY = player.position.y
                    newPlayerX = player.position.x
                    // 有人连接 则发送自己的消息
                    
                    // 每隔100ms去同步我的信息
                    setInterval(() => {
                        send({
                            code:'1005',
                            username:player.name,
                            playerInfo:{
                                position: {
                                    x: newPlayerX,
                                    y: newPlayerY
                                    // originX: newPlayerX,
                                    // originY: newPlayerY
                                },
                                animate:player.animate,
                                toward:player.toward,
                                isMove:player.isMove,
                                isBorn:player.isBorn
                            }
                        })
                    }, 30);
                    setTimeout(() => {
                        player.isBorn = true
                    }, 30);
                    playerUsernameList.add(message.username)
                }


            }
            else if (message.code === '2')
            {
                // 有人离开
                // noticeText.innerHTML += message.username + '离开游戏<br>';
                // 删除玩家
                playerUsernameList.delete(message.username)
                playerList.forEach((item, index) => {
                    if (item.name === message.username)
                    {
                        playerList.splice(index, 1)
                    }
                })
                console.log(playerList);
            }
            else if (message.code === '3')
            {
                console.log(message.username + '接收心跳成功');
            }
            else if (message.code === '4')
            {
                if (!playerUsernameList.has(message.username))
                {
                    playerUsernameList.add(message.username)
                    // 发现有新的玩家，本地创建一个对应的玩家实例
                    console.log('创建新玩家实例');
                    let playerInfo = new Sprite({
                        name:message.username,
                        position: {
                            x: message.playerInfo.position.x,
                            y: message.playerInfo.position.y,
                            originX: message.playerInfo.position.x,
                            originY: message.playerInfo.position.y
                        },
                        image: playerDownImage,
                        toward:message.playerInfo.toward,
                        frames: {
                            max: 3,
                            hold: 10
                        },
                        sprites: {
                            up: playerUpImage,
                            left: playerLeftImage,
                            right: playerRightImage,
                            down: playerDownImage
                        },
                        scale:2.5,
                        animate:message.playerInfo.animate
                    })
                    playerList.push(playerInfo)

                    // return
                }
                if (message.username !== username)
                {
                    playerList.forEach(element => {
                        if (element.name === message.username)
                        {
                            let rangeY = 0
                            let rangeX = 0
                            // 如果已经有了实例对象了，那么则只需要更新状态
                            if (message.playerInfo.isMove)
                            {
                                console.log('11111111');
                                rangeY = element.position.originY - message.playerInfo.position.y
                                rangeX = element.position.originX - message.playerInfo.position.x
                                // element.position.x = message.playerInfo.position.x
                                if (rangeX > 0)
                                {
                                    // 往左移动
                                    // element.position.x -= rangeX
                                    let length = Math.round(Math.abs(rangeX) / 3)
                                    for(let i = 0; i < length; i++)
                                    {
                                        element.position.x -= 3
                                    }
                                }
                                else
                                {
                                    // 往右移动
                                    // element.position.x += rangeX
                                    let length = Math.round(Math.abs(rangeX) / 3)
                                    for(let i = 0; i < length; i++)
                                    {
                                        element.position.x += 3
                                    }
                                }

                                if (rangeY > 0)
                                {
                                    // 往上移动
                                    // element.position.y -= rangeY
                                    let length = Math.round(Math.abs(rangeY) / 3)
                                    for(let i = 0; i < length; i++)
                                    {
                                        element.position.y -= 3
                                        console.log(element.position.y);
                                    }
                                    console.log(rangeY);
                                }
                                else
                                {
                                    // 往下移动
                                    // element.position.y += rangeY
                                    let length = Math.round(Math.abs(rangeY) / 3)
                                    for(let i = 0; i < length; i++)
                                    {
                                        element.position.y += 3
                                        console.log(element.position.y);
                                    }
                                    console.log(rangeY);
                                }
                                element.position.originX = message.playerInfo.position.x
                                element.position.originY = message.playerInfo.position.y
                        
                            }
                            else
                            {
                                // 取消移动了，重新赋值origin坐标
                                // 初始化新玩家的出生坐标
                                if (!message.playerInfo.isBorn)
                                {
                                    console.log('2223333');
                                    if (element.position.originX !== newPlayerX)
                                    {
                                        let rangeX = newPlayerX - element.position.originX
                                        let count = 0
                                        let length = Math.round(Math.abs(rangeX) / 3)
                                        if (rangeX === 0) return
                                        if (rangeX > 0)
                                        {
                                            for(let i = 0; i < length; i++)
                                            {
                                                count -= 3
                                            }
                                            element.position.x = element.position.x + count
                                            // element.position.originX = element.position.x + count
                                        }
                                        else
                                        {
                                            for(let i = 0; i < length; i++)
                                            {
                                                count += 3
                                            }
                                            element.position.x = element.position.x + count
                                            // element.position.originX = element.position.x + count
                                        }
                                    }
                                    if (element.position.originY !== newPlayerY)
                                    {
                                        let rangeY = newPlayerY - element.position.originY
                                        let count = 0
                                        let length = Math.round(Math.abs(rangeY) / 3)
                                        if (rangeY === 0) return
                                        if (rangeY > 0)
                                        {
                                            for(let i = 0; i < length; i++)
                                            {
                                                count -= 3
                                            }
                                            console.log(count);
                                            element.position.y = element.position.y + count
                                            // element.position.originY = element.position.y + count
                                        }
                                        else
                                        {
                                            for(let i = 0; i < length; i++)
                                            {
                                                count += 3
                                            }
                                            element.position.y = element.position.y + count
                                            // element.position.originY = element.position.y + count
                                        }
                                    }
                                    element.isBorn = true
                                }
                                
                                // element.position.originX = message.playerInfo.position.x
                                // element.position.originY = message.playerInfo.position.y
                                console.log('不动时候的坐标', element.position.originX, element.position.originY);
                            }
                            element.animate = message.playerInfo.animate
                            element.toward = message.playerInfo.toward
                            element.isMove = message.playerInfo.isMove
                            element.isBorn = message.playerInfo.isBorn
                            // console.log(element.position);
                        }
                    });
                }
                // console.log(playerList);
            }
        },
        (error) => 
        {
            console.log(error);
            // methods.reConnectSocket();
        },
        (code) => 
        {
            // if (data.forceFlag) return;
            // methods.reConnectSocket();
        })
    }
}




